<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SinmaJS 新功能演示</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .module {
            border: 1px solid #e0e0e0;
            margin: 15px 0;
            padding: 20px;
            border-radius: 8px;
            background: #fafafa;
        }
        .module h3 {
            margin-top: 0;
            color: #333;
            border-bottom: 2px solid #4CAF50;
            padding-bottom: 10px;
        }
        .demo-item {
            margin: 10px 0;
            padding: 10px;
            background: white;
            border-radius: 5px;
            border-left: 4px solid #2196F3;
        }
        .result {
            background: #e8f5e8;
            padding: 8px;
            margin: 5px 0;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            color: #2e7d32;
        }
        .error {
            background: #ffebee;
            color: #c62828;
        }
        button {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background: #45a049;
        }
        input, textarea {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin: 5px;
        }
        .file-input {
            margin: 10px 0;
        }
        .image-preview {
            max-width: 200px;
            max-height: 200px;
            border: 1px solid #ddd;
            margin: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎉 SinmaJS 新功能演示</h1>
        <p>基于 Hutool 启发的 6 个新模块功能演示</p>

        <!-- 1. 加密解密模块 -->
        <div class="module">
            <h3>🔒 Crypto 加密解密模块</h3>

            <div class="demo-item">
                <h4>Base64 编码/解码</h4>
                <input type="text" id="base64-input" placeholder="输入要编码的文本" value="Hello 中文测试">
                <button onclick="testBase64()">Base64编码/解码</button>
                <div id="base64-result" class="result"></div>
            </div>

            <div class="demo-item">
                <h4>MD5 哈希</h4>
                <input type="text" id="md5-input" placeholder="输入要哈希的文本" value="sinmajs">
                <button onclick="testMd5()">计算MD5</button>
                <div id="md5-result" class="result"></div>
            </div>

            <div class="demo-item">
                <h4>密码生成器</h4>
                <label>长度: <input type="number" id="pwd-length" value="12" min="4" max="50"></label>
                <label><input type="checkbox" id="pwd-upper" checked> 大写字母</label>
                <label><input type="checkbox" id="pwd-lower" checked> 小写字母</label>
                <label><input type="checkbox" id="pwd-numbers" checked> 数字</label>
                <label><input type="checkbox" id="pwd-symbols" checked> 特殊字符</label>
                <button onclick="testPasswordGenerator()">生成密码</button>
                <div id="password-result" class="result"></div>
            </div>
        </div>

        <!-- 2. JSON处理模块 -->
        <div class="module">
            <h3>📊 JSON 处理模块</h3>

            <div class="demo-item">
                <h4>JSON 路径操作</h4>
                <textarea id="json-input" rows="4" cols="50">{"user":{"profile":{"name":"张三","age":25},"settings":{"theme":"dark"}}}</textarea>
                <br>
                <input type="text" id="json-path" placeholder="路径 (如: user.profile.name)" value="user.profile.name">
                <button onclick="testJsonPath()">获取值</button>
                <button onclick="testJsonSet()">设置值</button>
                <div id="json-result" class="result"></div>
            </div>

            <div class="demo-item">
                <h4>JSON 格式化</h4>
                <button onclick="testJsonFormat()">格式化JSON</button>
                <button onclick="testJsonCompress()">压缩JSON</button>
                <div id="json-format-result" class="result"></div>
            </div>
        </div>

        <!-- 3. 文件处理模块 -->
        <div class="module">
            <h3>📁 File 文件处理模块</h3>

            <div class="demo-item">
                <h4>文件下载</h4>
                <button onclick="testDownloadText()">下载文本文件</button>
                <button onclick="testDownloadJson()">下载JSON文件</button>
                <button onclick="testDownloadCsv()">下载CSV文件</button>
                <div id="file-result" class="result"></div>
            </div>

            <div class="demo-item">
                <h4>文件信息检测</h4>
                <input type="text" id="filename-input" placeholder="输入文件名" value="example.jpg">
                <button onclick="testFileInfo()">检测文件信息</button>
                <div id="file-info-result" class="result"></div>
            </div>

            <div class="demo-item">
                <h4>文件大小格式化</h4>
                <input type="number" id="bytes-input" placeholder="输入字节数" value="1048576">
                <button onclick="testFileSize()">格式化大小</button>
                <div id="file-size-result" class="result"></div>
            </div>
        </div>

        <!-- 4. 缓存模块 -->
        <div class="module">
            <h3>💾 Cache 缓存模块</h3>

            <div class="demo-item">
                <h4>内存缓存测试</h4>
                <input type="text" id="cache-key" placeholder="缓存键" value="test-key">
                <input type="text" id="cache-value" placeholder="缓存值" value="测试数据">
                <input type="number" id="cache-ttl" placeholder="过期时间(毫秒)" value="5000">
                <br>
                <button onclick="testCacheSet()">设置缓存</button>
                <button onclick="testCacheGet()">获取缓存</button>
                <button onclick="testCacheClear()">清空缓存</button>
                <div id="cache-result" class="result"></div>
            </div>

            <div class="demo-item">
                <h4>函数缓存装饰器</h4>
                <button onclick="testMemoize()">测试函数缓存</button>
                <div id="memoize-result" class="result"></div>
            </div>
        </div>

        <!-- 5. 图片处理模块 -->
        <div class="module">
            <h3>🖼️ Image 图片处理模块</h3>

            <div class="demo-item">
                <h4>图片处理演示</h4>
                <p>由于浏览器安全限制，图片处理功能需要用户选择本地图片文件</p>
                <input type="file" id="image-input" accept="image/*" class="file-input">
                <br>
                <button onclick="testImageCompress()">压缩图片</button>
                <button onclick="testImageResize()">调整大小</button>
                <button onclick="testImageFilter()">应用滤镜</button>
                <div id="image-result" class="result"></div>
                <div id="image-preview"></div>
            </div>
        </div>

        <!-- 6. 转换器模块 -->
        <div class="module">
            <h3>🔄 Convert 转换器模块</h3>

            <div class="demo-item">
                <h4>类型转换</h4>
                <input type="text" id="convert-input" placeholder="输入值" value="123.45">
                <select id="convert-type">
                    <option value="string">字符串</option>
                    <option value="number">数字</option>
                    <option value="integer">整数</option>
                    <option value="boolean">布尔值</option>
                    <option value="array">数组</option>
                </select>
                <button onclick="testTypeConvert()">类型转换</button>
                <div id="convert-result" class="result"></div>
            </div>

            <div class="demo-item">
                <h4>进制转换</h4>
                <input type="number" id="number-input" placeholder="输入十进制数" value="255">
                <button onclick="testBaseConvert()">进制转换</button>
                <div id="base-result" class="result"></div>
            </div>

            <div class="demo-item">
                <h4>单位转换</h4>
                <input type="number" id="temp-input" placeholder="摄氏度" value="25">
                <button onclick="testTempConvert()">温度转换</button>
                <input type="number" id="length-input" placeholder="米" value="100">
                <button onclick="testLengthConvert()">长度转换</button>
                <div id="unit-result" class="result"></div>
            </div>
        </div>

        <div class="module">
            <h3>🧪 综合测试</h3>
            <button onclick="runAllTests()" style="background: #FF9800; font-size: 16px; padding: 12px 24px;">运行所有功能测试</button>
            <div id="all-tests-result" class="result"></div>
        </div>
    </div>

    <!-- 引入 SinmaJS -->
    <script src="../dist/sinma.js"></script>

    <script>
        // 1. 加密解密模块测试
        function testBase64() {
            const input = document.getElementById('base64-input').value;
            const encoded = sinma.base64Encode(input);
            const decoded = sinma.base64Decode(encoded);
            document.getElementById('base64-result').innerHTML =
                `原文: ${input}<br>编码: ${encoded}<br>解码: ${decoded}`;
        }

        function testMd5() {
            const input = document.getElementById('md5-input').value;
            const hash = sinma.md5(input);
            document.getElementById('md5-result').innerHTML =
                `原文: ${input}<br>MD5: ${hash}`;
        }

        function testPasswordGenerator() {
            const length = document.getElementById('pwd-length').value;
            const options = {
                includeUppercase: document.getElementById('pwd-upper').checked,
                includeLowercase: document.getElementById('pwd-lower').checked,
                includeNumbers: document.getElementById('pwd-numbers').checked,
                includeSymbols: document.getElementById('pwd-symbols').checked
            };
            const password = sinma.generatePassword(parseInt(length), options);
            document.getElementById('password-result').innerHTML =
                `生成的密码: ${password}<br>长度: ${password.length}`;
        }

        // 2. JSON处理模块测试
        function testJsonPath() {
            const jsonStr = document.getElementById('json-input').value;
            const path = document.getElementById('json-path').value;
            try {
                const obj = sinma.parseJson(jsonStr);
                const value = sinma.getByPath(obj, path);
                document.getElementById('json-result').innerHTML =
                    `路径 "${path}" 的值: ${JSON.stringify(value)}`;
            } catch (e) {
                document.getElementById('json-result').innerHTML = `错误: ${e.message}`;
                document.getElementById('json-result').className = 'result error';
            }
        }

        function testJsonSet() {
            const jsonStr = document.getElementById('json-input').value;
            const path = document.getElementById('json-path').value;
            try {
                const obj = sinma.parseJson(jsonStr);
                sinma.setByPath(obj, path, '新值 ' + Date.now());
                document.getElementById('json-input').value = sinma.toJsonString(obj, '{}', 2);
                document.getElementById('json-result').innerHTML =
                    `已设置路径 "${path}" 的值`;
            } catch (e) {
                document.getElementById('json-result').innerHTML = `错误: ${e.message}`;
                document.getElementById('json-result').className = 'result error';
            }
        }

        function testJsonFormat() {
            const jsonStr = document.getElementById('json-input').value;
            try {
                const formatted = sinma.formatJson(jsonStr);
                document.getElementById('json-format-result').innerHTML =
                    `<pre>${formatted}</pre>`;
            } catch (e) {
                document.getElementById('json-format-result').innerHTML = `错误: ${e.message}`;
            }
        }

        function testJsonCompress() {
            const jsonStr = document.getElementById('json-input').value;
            try {
                const compressed = sinma.compressJson(jsonStr);
                document.getElementById('json-format-result').innerHTML =
                    `压缩后: ${compressed}`;
            } catch (e) {
                document.getElementById('json-format-result').innerHTML = `错误: ${e.message}`;
            }
        }

        // 3. 文件处理模块测试
        function testDownloadText() {
            const content = "这是一个测试文本文件\n生成时间: " + new Date().toLocaleString();
            sinma.downloadTextFile(content, 'test.txt');
            document.getElementById('file-result').innerHTML = '文本文件下载已开始';
        }

        function testDownloadJson() {
            const data = {
                name: '测试数据',
                timestamp: Date.now(),
                items: ['项目1', '项目2', '项目3']
            };
            sinma.downloadJsonFile(data, 'test.json');
            document.getElementById('file-result').innerHTML = 'JSON文件下载已开始';
        }

        function testDownloadCsv() {
            const data = [
                ['姓名', '年龄', '城市'],
                ['张三', '25', '北京'],
                ['李四', '30', '上海'],
                ['王五', '28', '广州']
            ];
            sinma.downloadCsvFile(data, 'test.csv');
            document.getElementById('file-result').innerHTML = 'CSV文件下载已开始';
        }

        function testFileInfo() {
            const filename = document.getElementById('filename-input').value;
            const extension = sinma.getFileExtension(filename);
            const name = sinma.getFileName(filename);
            const mimeType = sinma.getMimeType(filename);
            const isImage = sinma.isImageFile(filename);
            const isVideo = sinma.isVideoFile(filename);

            document.getElementById('file-info-result').innerHTML =
                `文件名: ${filename}<br>
                扩展名: ${extension}<br>
                文件名(无扩展名): ${name}<br>
                MIME类型: ${mimeType}<br>
                是否图片: ${isImage}<br>
                是否视频: ${isVideo}`;
        }

        function testFileSize() {
            const bytes = document.getElementById('bytes-input').value;
            const formatted = sinma.formatFileSize(parseInt(bytes));
            document.getElementById('file-size-result').innerHTML =
                `${bytes} 字节 = ${formatted}`;
        }

        // 4. 缓存模块测试
        function testCacheSet() {
            const key = document.getElementById('cache-key').value;
            const value = document.getElementById('cache-value').value;
            const ttl = document.getElementById('cache-ttl').value;

            sinma.setMemoryCache(key, value, parseInt(ttl));
            document.getElementById('cache-result').innerHTML =
                `已设置缓存: ${key} = ${value} (${ttl}ms后过期)`;
        }

        function testCacheGet() {
            const key = document.getElementById('cache-key').value;
            const value = sinma.getMemoryCache(key);
            document.getElementById('cache-result').innerHTML =
                `缓存值: ${value === undefined ? '未找到或已过期' : value}`;
        }

        function testCacheClear() {
            sinma.clearMemoryCache();
            document.getElementById('cache-result').innerHTML = '已清空所有缓存';
        }

        function testMemoize() {
            // 创建一个计算斐波那契数列的函数
            const fibonacci = sinma.memoize(function(n) {
                if (n <= 1) return n;
                return fibonacci(n - 1) + fibonacci(n - 2);
            });

            const start = performance.now();
            const result = fibonacci(40);
            const end = performance.now();

            document.getElementById('memoize-result').innerHTML =
                `fibonacci(40) = ${result}<br>
                计算时间: ${(end - start).toFixed(2)}ms<br>
                (第二次调用会更快，因为有缓存)`;
        }

        // 5. 图片处理模块测试
        function testImageCompress() {
            const fileInput = document.getElementById('image-input');
            if (!fileInput.files[0]) {
                document.getElementById('image-result').innerHTML = '请先选择图片文件';
                return;
            }

            const file = fileInput.files[0];
            sinma.compressImage(file, { quality: 0.7, maxWidth: 800 })
                .then(blob => {
                    const url = URL.createObjectURL(blob);
                    document.getElementById('image-result').innerHTML =
                        `原文件大小: ${sinma.formatFileSize(file.size)}<br>
                        压缩后大小: ${sinma.formatFileSize(blob.size)}<br>
                        压缩率: ${((1 - blob.size / file.size) * 100).toFixed(1)}%`;

                    const img = document.createElement('img');
                    img.src = url;
                    img.className = 'image-preview';
                    img.alt = '压缩后的图片';
                    document.getElementById('image-preview').innerHTML = '';
                    document.getElementById('image-preview').appendChild(img);
                })
                .catch(e => {
                    document.getElementById('image-result').innerHTML = `错误: ${e.message}`;
                });
        }

        function testImageResize() {
            const fileInput = document.getElementById('image-input');
            if (!fileInput.files[0]) {
                document.getElementById('image-result').innerHTML = '请先选择图片文件';
                return;
            }

            const file = fileInput.files[0];
            sinma.resizeImage(file, { width: 300, height: 300 })
                .then(blob => {
                    const url = URL.createObjectURL(blob);
                    document.getElementById('image-result').innerHTML =
                        `已调整为 300x300 像素`;

                    const img = document.createElement('img');
                    img.src = url;
                    img.className = 'image-preview';
                    img.alt = '调整大小后的图片';
                    document.getElementById('image-preview').innerHTML = '';
                    document.getElementById('image-preview').appendChild(img);
                })
                .catch(e => {
                    document.getElementById('image-result').innerHTML = `错误: ${e.message}`;
                });
        }

        function testImageFilter() {
            const fileInput = document.getElementById('image-input');
            if (!fileInput.files[0]) {
                document.getElementById('image-result').innerHTML = '请先选择图片文件';
                return;
            }

            const file = fileInput.files[0];
            sinma.toGrayscale(file)
                .then(blob => {
                    const url = URL.createObjectURL(blob);
                    document.getElementById('image-result').innerHTML = '已应用灰度滤镜';

                    const img = document.createElement('img');
                    img.src = url;
                    img.className = 'image-preview';
                    img.alt = '灰度滤镜图片';
                    document.getElementById('image-preview').innerHTML = '';
                    document.getElementById('image-preview').appendChild(img);
                })
                .catch(e => {
                    document.getElementById('image-result').innerHTML = `错误: ${e.message}`;
                });
        }

        // 6. 转换器模块测试
        function testTypeConvert() {
            const input = document.getElementById('convert-input').value;
            const type = document.getElementById('convert-type').value;

            let result;
            switch (type) {
                case 'string':
                    result = sinma.toString(input);
                    break;
                case 'number':
                    result = sinma.toNumber(input);
                    break;
                case 'integer':
                    result = sinma.toInteger(input);
                    break;
                case 'boolean':
                    result = sinma.toBoolean(input);
                    break;
                case 'array':
                    result = sinma.toArray(input);
                    break;
            }

            document.getElementById('convert-result').innerHTML =
                `原值: ${input} (${typeof input})<br>
                转换为${type}: ${JSON.stringify(result)} (${typeof result})`;
        }

        function testBaseConvert() {
            const num = document.getElementById('number-input').value;
            const decimal = parseInt(num);

            document.getElementById('base-result').innerHTML =
                `十进制: ${decimal}<br>
                二进制: ${sinma.decimalToBinary(decimal)}<br>
                八进制: ${sinma.decimalToOctal(decimal)}<br>
                十六进制: ${sinma.decimalToHex(decimal)}`;
        }

        function testTempConvert() {
            const celsius = document.getElementById('temp-input').value;
            const fahrenheit = sinma.celsiusToFahrenheit(parseFloat(celsius));
            const kelvin = sinma.celsiusToKelvin(parseFloat(celsius));

            document.getElementById('unit-result').innerHTML =
                `${celsius}°C = ${fahrenheit.toFixed(2)}°F = ${kelvin.toFixed(2)}K`;
        }

        function testLengthConvert() {
            const meters = document.getElementById('length-input').value;
            const feet = sinma.metersToFeet(parseFloat(meters));
            const km = parseFloat(meters) / 1000;
            const miles = sinma.kilometersToMiles(km);

            document.getElementById('unit-result').innerHTML +=
                `<br>${meters}米 = ${feet.toFixed(2)}英尺 = ${km}公里 = ${miles.toFixed(2)}英里`;
        }

        // 综合测试
        function runAllTests() {
            const results = [];

            // 测试各个模块的核心功能
            try {
                // Crypto 模块
                const md5Test = sinma.md5('test');
                results.push(`✓ Crypto: MD5哈希正常 (${md5Test.substring(0, 8)}...)`);

                const base64Test = sinma.base64Decode(sinma.base64Encode('test'));
                results.push(`✓ Crypto: Base64编解码正常 (${base64Test})`);

                // JSON 模块
                const jsonObj = { test: { value: 123 } };
                const pathValue = sinma.getByPath(jsonObj, 'test.value');
                results.push(`✓ JSON: 路径访问正常 (${pathValue})`);

                // File 模块
                const fileSize = sinma.formatFileSize(1048576);
                results.push(`✓ File: 文件大小格式化正常 (${fileSize})`);

                // Cache 模块
                sinma.setMemoryCache('test', 'value');
                const cacheValue = sinma.getMemoryCache('test');
                results.push(`✓ Cache: 内存缓存正常 (${cacheValue})`);

                // Convert 模块
                const converted = sinma.toString(123);
                results.push(`✓ Convert: 类型转换正常 (${converted})`);

                const binary = sinma.decimalToBinary(10);
                results.push(`✓ Convert: 进制转换正常 (${binary})`);

                results.push('<br><strong>🎉 所有新功能模块测试通过！</strong>');

            } catch (e) {
                results.push(`✗ 测试失败: ${e.message}`);
            }

            document.getElementById('all-tests-result').innerHTML = results.join('<br>');
        }

        // 页面加载完成后自动运行综合测试
        window.onload = function() {
            setTimeout(runAllTests, 500);
        };
    </script>
</body>
</html>